package com.lgt_enterprise_android.view.pages.b;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.flexbox.FlexboxLayout;
import com.lgt_enterprise_android.Constant;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.adapter.MyStaffAdapter2;
import com.lgt_enterprise_android.utils.BasicHttp;
import com.lgt_enterprise_android.utils.HttpManager;
import com.lgt_enterprise_android.utils.StringUtil;
import com.lgt_enterprise_android.view.widgets.weekcalendar.WeekCalendarView;
import com.util.AppUtil;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class ArrangeJobManager {

    private ArrangeJobActivity mContext;

    private View viewBottom;

    private WeekCalendarView mWeekCalendarView;

    ListView listView, listviewQB;

    private TextView txtRangeTime, txtAlreadyCount, txtDelete, txtSetting;

    private LinearLayout containerLeft, containerRight, containerRight2;
    private FlexboxLayout mFlexboxLayout;
    private RadioButton rb1, rb2;
    private RadioGroup rg;

    private int currentRow, startTime, endTime;

    private EditText edNeedQPMembers, edWage;

    private InnerAdapter mInnerAdapter;

    public ArrayList<String> alreadySel = new ArrayList<>();

    private NiceSpinner niceSpinner;
    private List<String> datasetSex;

    private int type = -1; //1是排班 2是抢班 3是混合

    private Map<String, JSONArray> mapPosSkill = new HashMap<>();

    private boolean hasStaff = false;//是否有人抢班

    public void bind(ArrangeJobActivity _mContext) {
        mContext = _mContext;

        initView();
        bindEvent();
        getMembers();
    }

    private void initView() {
        mWeekCalendarView = (WeekCalendarView) mContext.findViewById(R.id.weekCalendarView);
        txtRangeTime = (TextView) mContext.findViewById(R.id.txt_range_time);
        txtAlreadyCount = (TextView) mContext.findViewById(R.id.txt_alredy_select);
        txtSetting = (TextView) mContext.findViewById(R.id.txt_setting);
        txtDelete = (TextView) mContext.findViewById(R.id.txt_delete_paiban);

        edNeedQPMembers = (EditText) mContext.findViewById(R.id.ed_qb_members);
        edWage = (EditText) mContext.findViewById(R.id.ed_wage);
        mFlexboxLayout = (FlexboxLayout) mContext.findViewById(R.id.flex_box);

        containerLeft = mContext.findViewById(R.id.lin_pb);
        containerRight = mContext.findViewById(R.id.lin_qb);
        containerRight2 = mContext.findViewById(R.id.lin_qb2);

        niceSpinner = (NiceSpinner) mContext.findViewById(R.id.nice_spinner);
        datasetSex = Arrays.asList("不限", "   男", "   女");
        niceSpinner.attachDataSource(datasetSex);
        initTopButton();

        listView = (ListView) mContext.findViewById(R.id.list_members);
        listviewQB = (ListView) mContext.findViewById(R.id.listview_qb);

        viewBottom = mContext.findViewById(R.id.lin_bottom);

        edNeedQPMembers.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.toString().startsWith("0") && editable.toString().trim().length()>1){
                    edNeedQPMembers.setText(editable.toString().substring(1,editable.length()));
                }
            }
        });

        edWage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.toString().startsWith("0") && editable.toString().trim().length()>1){
                    edWage.setText(editable.toString().substring(1,editable.length()));
                }
            }
        });
    }

    private void getMembers() {
        HttpManager.getWorkerList(mContext, 1, 100, new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(Object resonseObj) {
                JSONArray jsonArray = ((JSONObject) resonseObj).getJSONArray("list");
                mInnerAdapter = new InnerAdapter(mContext, jsonArray);
                listView.setAdapter(mInnerAdapter);
            }

            @Override
            public void onFailure(String mes) {

            }
        });
    }

    private void bindEvent() {
        txtDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int j = startTime; j < endTime; j++) {
                    mContext.grid_data[currentRow][j] = 0;
                    mContext.mapPosMem.put(currentRow + "#" + j, "");
                    mContext.closeRightDialog();
                }
            }
        });

        txtSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(txtSetting.getText().equals("抢班列表")){
                    txtSetting.setText("设置");
                    containerRight2.setVisibility(View.VISIBLE);
                    containerRight.setVisibility(View.GONE);
                }else{
                    txtSetting.setText("抢班列表");
                    containerRight.setVisibility(View.VISIBLE);
                    containerRight2.setVisibility(View.GONE);
                }


            }
        });

        mContext.findViewById(R.id.img_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mWeekCalendarView.goToNextWeek();
            }
        });

        mContext.findViewById(R.id.img_previous).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mWeekCalendarView.goToPreiousWeek();
            }
        });

        mContext.findViewById(R.id.txt_right_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String txtNum = edNeedQPMembers.getText().toString();

                for (int i = 0; i < mContext.listJobs.size(); i++) {
                    for (int j = 0; j < Constant.Grid_column_count; j++) {
                        if (mContext.grid_data[i][j] > 100) {
                            mContext.grid_data[i][j] = 0;
                        }
                    }
                }

                if (!StringUtil.isEmpty(txtNum) && Integer.parseInt(txtNum) > 0 && alreadySel.size() > 0) {
                    saveMixture();
                } else if (alreadySel.size() > 0) {
                    savePaiban();
                } else if (!StringUtil.isEmpty(txtNum) && Integer.parseInt(txtNum) > 0) {
                    saveQiangban();
                }
            }
        });
    }

    public String getTimeRange() {
        return startTime + "#" + (endTime - 1);
    }

    // if strMembers = '*' , means keep same, empty means first create
    private void configInfo(String dataInfo) {
        setFlexView();
        if (type == 1) {
            rb1.setChecked(true);
            txtSetting.setVisibility(View.GONE);
            txtDelete.setVisibility(View.VISIBLE);
            containerRight.setVisibility(View.GONE);
            containerLeft.setVisibility(View.VISIBLE);
            if (!StringUtil.isEmpty(dataInfo)) {
                alreadySel.clear();
                for (String str : dataInfo.split("#")) {
                    if (!StringUtil.isEmpty(str)) {
                        alreadySel.add(str);
                    }
                }
            }
            edWage.setText("");
            edNeedQPMembers.setText("");
        } else if (type == 2) {

            alreadySel.clear();

            if (!StringUtil.isEmpty(dataInfo)) {
                viewBottom.setVisibility(View.VISIBLE);
                String alreadyQBStaffId = dataInfo.split("#")[4];
                if ("?".equals(alreadyQBStaffId)) {
                    containerRight.setVisibility(View.VISIBLE);
                    txtSetting.setVisibility(View.GONE);
                    txtDelete.setVisibility(View.VISIBLE);
                    viewBottom.setVisibility(View.VISIBLE);
                    containerRight2.setVisibility(View.GONE);
                } else {
                    //当前抢班已有人员抢了
                    hasStaff = true;
                    JSONArray jsonArray = new JSONArray();
                    String[] arrIDs = alreadyQBStaffId.split(",");
                    for (String str : arrIDs) {
                        jsonArray.add(mContext.mapStaff.get(str));
                    }
                    MyStaffAdapter2 adapter = new MyStaffAdapter2(mContext, jsonArray);
                    listviewQB.setAdapter(adapter);

                    mContext.findViewById(R.id.txt_right_save).setVisibility(View.GONE);
                    viewBottom.setVisibility(View.GONE);
                    containerRight.setVisibility(View.GONE);
                    txtDelete.setVisibility(View.GONE); //已抢排班不能删除
                    txtSetting.setVisibility(View.VISIBLE);
                    containerRight2.setVisibility(View.VISIBLE);
                }
                setQbInfo(dataInfo);
            }
            rb2.setChecked(true);
        } else if (type == 3) {
            if (!StringUtil.isEmpty(dataInfo)) {
                String[] arrAll = dataInfo.split("&");
                String paiBan = arrAll[0];
                if (!StringUtil.isEmpty(paiBan)) {
                    alreadySel.clear();
                    for (String str : paiBan.split("#")) {
                        if (!StringUtil.isEmpty(str)) {
                            alreadySel.add(str);
                        }
                    }
                }

                String qBan = arrAll[1];
                String alreadyQBStaffId = qBan.split("#")[4];
                if (!"?".equals(alreadyQBStaffId)) {
                    hasStaff = true;
                    viewBottom.setVisibility(View.GONE);

                    JSONArray jsonArray = new JSONArray();
                    String[] arrIDs = alreadyQBStaffId.split(",");
                    for (String str : arrIDs) {
                        jsonArray.add(mContext.mapStaff.get(str));
                    }
                    MyStaffAdapter2 adapter = new MyStaffAdapter2(mContext, jsonArray);
                    listviewQB.setAdapter(adapter);
                }
                setQbInfo(arrAll[1]);
                if (mContext.defaultType == 1) {
                    rb1.setChecked(true);
                    txtSetting.setVisibility(View.GONE);
                } else {
                    rb2.setChecked(true);
                }
            }
        }
    }

    // if strMembers = '*' , means keep same, empty means first create
    public void showWin(int _startTime, int _endTime, int row, int _type, String dataInfo) {
        rb1.setChecked(true);
        startTime = _startTime;
        endTime = _endTime + 1;
        txtRangeTime.setText(startTime + ":00 至 " + endTime + ":00");
        currentRow = row;
        mContext.findViewById(R.id.txt_right_save).setVisibility(View.VISIBLE);

        mInnerAdapter.notifyDataSetChanged();
        hasStaff = false;

        if ("*".equals(dataInfo)) {
            return;
        }

        MyStaffAdapter2 adapter = new MyStaffAdapter2(mContext, new JSONArray());
        listviewQB.setAdapter(adapter);

        if (StringUtil.isEmpty(dataInfo)) {
            alreadySel.clear();
            edWage.setText("");
            edNeedQPMembers.setText("");

            for (int i = 0, m = mFlexboxLayout.getChildCount(); i < m; i++) {
                View view = mFlexboxLayout.getFlexItemAt(i);

                if (view instanceof CheckBox) {
                    CheckBox checkBox = (CheckBox) view;
                    checkBox.setChecked(false);
                    checkBox.setTextColor(0xFF999999);
                }
            }
            viewBottom.setVisibility(View.GONE);
        }else{
            viewBottom.setVisibility(View.VISIBLE);
        }

        this.type = _type;
        initFlexData(dataInfo);
    }

    //人数#性别#技能#薪资#已抢灵工ID
    private void setQbInfo(String info) {
        if (StringUtil.isEmpty(info)) {
            return;
        }

        String[] arr = info.split("#");

        if (arr.length < 5) {
            return;
        }

        edNeedQPMembers.setText(arr[0]);
        edWage.setText(arr[3]);

        niceSpinner.setSelectedIndex(Integer.parseInt(arr[1]));

        List<String> list = new ArrayList<>();

        if (arr.length == 5 && !StringUtil.isEmpty(arr[2])) {
            list = Arrays.asList(arr[2].split(","));
        }

        for (int i = 0, m = mFlexboxLayout.getChildCount(); i < m; i++) {
            View view = mFlexboxLayout.getFlexItemAt(i);

            if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;

                if (list.contains(checkBox.getTag().toString())) {
                    checkBox.setChecked(true);
                    checkBox.setTextColor(0xffffffff);
                } else {
                    checkBox.setChecked(false);
                    checkBox.setTextColor(0xFF999999);
                }
            }
        }

    }

    public boolean enableArrnage() {
        HashSet<String> set = new HashSet<>();

        for (int row = 0; row < mContext.listJobs.size(); row++) {
            if (row == currentRow) {
                continue;
            }

            for (int col = 0; col < Constant.Grid_column_count; col++) {
                if (mContext.grid_data[row][col] == 1) {//排班
                    if (mContext.mapPosMem.containsKey(row + "#" + col)) {
                        String mems = mContext.mapPosMem.get(row + "#" + col);
                        for (String _str : mems.split("#")) {
                            set.add(col + "-" + _str);
                        }
                    }
                } else if (mContext.grid_data[row][col] == 3) {
                    if (mContext.mapPosMem.containsKey(row + "#" + col)) {
                        String mems = mContext.mapPosMem.get(row + "#" + col).split("&")[0];
                        for (String _str : mems.split("#")) {
                            set.add(col + "-" + _str);
                        }
                    }
                }
            }
        }

        for (int j = startTime; j < endTime; j++) {
            for (int i = 0; i < alreadySel.size(); i++) {
                if (set.contains(j + "-" + alreadySel.get(i))) {
                    Toast.makeText(mContext, "排班冲突", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
        }

        return true;
    }

    private void savePaiban() {
        if (alreadySel.size() == 0) {
            mContext.showToast("请选择员工");
        } else {
            String str = "";
            for (int i = 0; i < alreadySel.size(); i++) {
                if (i == alreadySel.size() - 1) {
                    str += alreadySel.get(i);
                } else {
                    str += alreadySel.get(i) + "#";
                }
            }

            if (enableArrnage()) {
                for (int j = startTime; j < endTime; j++) {
                    mContext.grid_data[currentRow][j] = 1;
                    mContext.mapPosMem.put(currentRow + "#" + j, str);
                }
                mContext.closeRightDialog();
            }
        }
    }

    private void saveQiangban() {
        String number = edNeedQPMembers.getText().toString();
        String wage = edWage.getText().toString();

        if (StringUtil.isEmpty(number)) {
            mContext.showToast("缺岗人数不能为空");
            return;
        }

        if ("0".equals(number)) {
            mContext.showToast("缺岗人数不能为0");
            return;
        }

        if (StringUtil.isEmpty(wage)) {
            mContext.showToast("薪资不能为空");
            return;
        }

        if ("0".equals(wage)) {
            mContext.showToast("薪资不能为0");
            return;
        }

        String strSkills = "";

        for (int i = 0, m = mFlexboxLayout.getChildCount(); i < m; i++) {
            View view = mFlexboxLayout.getFlexItemAt(i);

            if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    strSkills += checkBox.getTag().toString() + ",";
                }
            }
        }

        if (strSkills.length() > 0) {
            strSkills = strSkills.substring(0, strSkills.length() - 1);
        } else {
            strSkills = "?";
        }

        String prop = number + "#" + niceSpinner.getSelectedIndex() + "#" + strSkills + "#" + wage + "#?"; //人数#性别#技能#薪资

        for (int j = startTime; j < endTime; j++) {
            mContext.grid_data[currentRow][j] = 2;
            mContext.mapPosMem.put(currentRow + "#" + j, prop);
        }
        mContext.closeRightDialog();
    }

    private void saveMixture() {
        String strPaiBan = "";
        for (int i = 0; i < alreadySel.size(); i++) {
            if (i == alreadySel.size() - 1) {
                strPaiBan += alreadySel.get(i);
            } else {
                strPaiBan += alreadySel.get(i) + "#";
            }
        }

        if (!enableArrnage()) {
            return;
        }


        String number = edNeedQPMembers.getText().toString();
        String strSkills = "";

        for (int i = 0, m = mFlexboxLayout.getChildCount(); i < m; i++) {
            View view = mFlexboxLayout.getFlexItemAt(i);

            if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    strSkills += checkBox.getTag().toString() + ",";
                }
            }
        }

        if (strSkills.length() > 0) {
            strSkills = strSkills.substring(0, strSkills.length() - 1);
        } else {
            strSkills = "?";
        }

        String strQB = number + "#" + niceSpinner.getSelectedIndex() + "#" + strSkills + "#" + edWage.getText().toString() + "#?";//人数#性别#技能#薪资#已抢班次灵工ID

        for (int j = startTime; j < endTime; j++) {
            mContext.grid_data[currentRow][j] = 3;
            mContext.mapPosMem.put(currentRow + "#" + j, strPaiBan + "&" + strQB);
        }
        mContext.closeRightDialog();
    }

    private void initTopButton() {
        rb1 = (RadioButton) mContext.findViewById(R.id.rd1);
        rb2 = (RadioButton) mContext.findViewById(R.id.rd2);

        SpannableStringBuilder spannable = new SpannableStringBuilder("人手不够，发布抢班");

        spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#FF9900")),
                5, 9,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        TextView txtPublish = (TextView) mContext.findViewById(R.id.txt_publish);
        txtPublish.setText(spannable);
        txtPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rb2.setChecked(true);
            }
        });

        rg = (RadioGroup) mContext.findViewById(R.id.rg);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (radioGroup.getCheckedRadioButtonId() == R.id.rd1) {
                    containerLeft.setVisibility(View.VISIBLE);
                    containerRight.setVisibility(View.GONE);
                    containerRight2.setVisibility(View.GONE);
                    rb1.setTextColor(mContext.getResources().getColor(R.color.text_black));
                    rb2.setTextColor(0xFF9CA3A9);
                } else {
                    if(hasStaff){
                        containerRight2.setVisibility(View.VISIBLE);
                        containerRight.setVisibility(View.GONE);
                        viewBottom.setVisibility(View.VISIBLE);
                        txtSetting.setVisibility(View.VISIBLE);
                        txtDelete.setVisibility(View.GONE);
                    }else{
                        containerRight.setVisibility(View.VISIBLE);
                        containerRight2.setVisibility(View.GONE);
                    }

                    containerLeft.setVisibility(View.GONE);
                    rb1.setTextColor(0xFF9CA3A9);
                    rb2.setTextColor(mContext.getResources().getColor(R.color.text_black));
                }
            }
        });
    }

    private void initFlexData(final String dataInfo) {
        final String pos = mContext.mapPosition.get(mContext.listJobs.get(currentRow));
        if (mapPosSkill.containsKey(pos)) {
            configInfo(dataInfo);
        } else {
            HttpManager.getSkillsByPosition(mContext, pos, new BasicHttp.IMyCallBack() {
                @Override
                public void onResponse(Object resonseObj) {
                    JSONArray arr = (JSONArray) resonseObj;
                    mapPosSkill.put(pos, arr);
                    configInfo(dataInfo);
                }

                @Override
                public void onFailure(String mes) {

                }
            });
        }
    }

    private void setFlexView() {
        mFlexboxLayout.removeAllViews();
        FlexboxLayout.LayoutParams lp = new FlexboxLayout.LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, FlexboxLayout.LayoutParams.WRAP_CONTENT);

        String pos = mContext.mapPosition.get(mContext.listJobs.get(currentRow));

        JSONArray jsonArray = mapPosSkill.get(pos);

        if (jsonArray == null) return;

        lp.leftMargin = AppUtil.getdensityIntDpi(mContext) * 10;
        lp.topMargin = AppUtil.getdensityIntDpi(mContext) * 10;
//        String[] arrSkils = new String[]{"懂普通话", "漂亮", "大长腿", "会英语", "会做饭"};
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            final CheckBox ch = new CheckBox(mContext);
            ch.setBackground(mContext.getDrawable(R.drawable.selecter_skill));
            ch.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));// 通过透明度的方式.
            ch.setText(jsonObject.getString("tagContent"));
            ch.setTextSize(13);
//            ch.setPadding(AppUtil.getdensityIntDpi(mContext)*15,AppUtil.getdensityIntDpi(mContext)*2,AppUtil.getdensityIntDpi(mContext)*5,AppUtil.getdensityIntDpi(mContext)*2);
            ch.setTag(jsonObject.getString("tagId"));
            ch.setTextColor(0xFF999999);
            ch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ch.isChecked()) {
                        ch.setTextColor(0xffffffff);
                    } else {
                        ch.setTextColor(0xFF999999);
                    }
                }
            });

            ch.setPadding(AppUtil.getdensityIntDpi(mContext) * 8, AppUtil.getdensityIntDpi(mContext) * 5, AppUtil.getdensityIntDpi(mContext) * 8, AppUtil.getdensityIntDpi(mContext) * 5);
            mFlexboxLayout.addView(ch, lp);
        }
    }

    class InnerAdapter extends BaseAdapter {
        private JSONArray jsonArray;
        private Context mContext;

        public InnerAdapter(Context _mContext, JSONArray _jsonArray) {
            jsonArray = _jsonArray;
            mContext = _mContext;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public int getCount() {
            return jsonArray.size();
        }

        @Override
        public View getView(final int pos, View convertView, ViewGroup viewGroup) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_arrange_inner, null);
                holder = new ViewHolder();

                holder.rb = (CheckBox) convertView.findViewById(R.id.radio);
                holder.txtName = (TextView) convertView.findViewById(R.id.txt_name);
                holder.txtGender = (TextView) convertView.findViewById(R.id.txt_gender);
                holder.txtAge = (TextView) convertView.findViewById(R.id.txt_age);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            JSONObject jo = jsonArray.getJSONObject(pos).getJSONObject("workerInfo");

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    holder.rb.setChecked(!holder.rb.isChecked());
                }
            });

            final String name = jo.getString("empName");
            final String id = jo.getString("id");

            convertView.setEnabled(true);
            holder.rb.setVisibility(View.VISIBLE);
            for (int i = startTime; i < endTime; i++) {
                if (((ArrangeJobActivity) mContext).setAlreadyMembers.contains(i + "-" + id)) {
                    convertView.setEnabled(false);
                    holder.rb.setVisibility(View.INVISIBLE);
                    break;
                }
            }

            holder.rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        if (!alreadySel.contains(id)) {
                            alreadySel.add(id);
                        }
                    } else {
                        alreadySel.remove(id);
                    }
                    txtAlreadyCount.setText("已选择" + alreadySel.size() + "人");
                }
            });

            if (alreadySel.contains(id)) {
                holder.rb.setChecked(true);
            } else {
                holder.rb.setChecked(false);
            }

            holder.txtName.setText(name);
            int gender = jo.getIntValue("gender");
            if (gender == 1) {
                holder.txtGender.setText("男");
            } else if (gender == 2) {
                holder.txtGender.setText("女");
            } else {
                holder.txtGender.setText("");
            }

            holder.txtAge.setText(jo.getString("age"));

            return convertView;
        }

        class ViewHolder {
            public CheckBox rb;
            public TextView txtName;
            public TextView txtGender;
            public TextView txtAge;
        }
    }
}

